#include "game.h"
#include "ui_game.h"
#include "gameinfo.h"
#include "enemy.h"
#include "turret.h"
#include "bullet.h"
#include "mainwindow.h"
#include "option.h"
#include "boom.h"
#include <QPainter>
#include <QTimer>
#include <QDebug>
#include <levelup.h>
#include <gameover.h>
Game::Game(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Game)
{
    ui->setupUi(this);
    //pmainwindow=mainparent;

    //loadscene(id);

    qDebug()<<"game_start1";

    //gif初始化
    gif[0]=new QMovie(":/gif/enemy_0.gif");
    gif[0]->start();
    startTimer(120);
}

Game::~Game()
{
    delete ui;
}

void Game::updateMap()
{
    i++;

    if(current_wave==wave) //敌人全被消灭
    {
        win();
    }
    else if(currEneNum==0)   //当前波敌人全部消灭
    {
        current_wave++;
        currEneNum=gameinfo->scene[id].nextwave[current_wave]-
                gameinfo->scene[id].nextwave[current_wave-1];
        QTimer::singleShot(5000,this,SLOT(nextwave()));
    }
    //qDebug()<<"eneNum"<<eneNum;
    for(int i=0;i<turret_list.size();i++)
    {
        turret_list.at(i)->UpdateMap();
    }

    for(int i=0;i<enemy_list.size();i++)
    {
        enemy_list.at(i)->UpdateMap();
    }

    for(int i=0;i<bullet_list.size();i++)
    {
        bullet_list.at(i)->UpdateMap();
    }
    checkHp();
    ui->money->setText(QString("%1").arg(money));
    ui->monster->setText(QString("%1/%2").arg(enemy_list.size()).arg(gameinfo->scene[id].enemy_number));
    update();
}

void Game::loadscene(int id)
{
    i=0;
    mouseType=0;
    current_wave=0;
    timeScale=1;
    ui->toolB_2->setVisible(false);
    gameinfo=new GameInfo();
    //场景预加载
    eneNum=0;
    levelUI=new Levelup(this);
    //原初始函数结束

    //清空数据
    for(int i=0;i<turret_list.size();i++)
    {
        delete turret_list.at(i);
    }
    turret_list.clear();

    for(int i=0;i<enemy_list.size();i++)
    {
        delete enemy_list.at(i);
    }
    enemy_list.clear();

    for(int i=0;i<bullet_list.size();i++)
    {
        delete bullet_list.at(i);
    }
    bullet_list.clear();



    switch(id)
    {
        case 1:{
        this->setStyleSheet("QWidget#Game{"
                                   "background-image: url(:/img/bg_1.png);"
                                   "}");
        this->id=1;
        bg.load(":/img/bg_1");
        maxHp=10;
        currentHp=maxHp;
        money=300;
        currEneNum=gameinfo->scene[1].nextwave[0];
        this->wave=gameinfo->scene[1].wave;
        break;
        }
        case 2:{
        this->setStyleSheet("QWidget#Game{"
                                   "background-image: url(:/img/bg_2.png);"
                                   "}");
        this->id=2;
        bg.load(":/img/bg_2");
        maxHp=10;
        currentHp=maxHp;
        money=300;
        currEneNum=gameinfo->scene[2].nextwave[0];
        this->wave=gameinfo->scene[2].wave;
        break;
        }

    }
    ui->label->setText(QString("%1/%2").arg(currentHp).arg(maxHp));
    QTimer::singleShot(5000,this,SLOT(nextwave()));

    if(!init)
    //原初始函数
    {
        timer = new QTimer(this);
        connect(timer, SIGNAL(timeout()), this, SLOT(updateMap()));
        init=true;
    }
    timer->start(30);
}

void Game::win()
{
    //qDebug()<<"you win";
    if(mainwindow->scene_number==id)mainwindow->scene_number++;

    Pause();
    Gameover go(mainwindow);
    go.win();
    go.exec();

}

void Game::lose()
{
    //qDebug()<<"you lose";
    Pause();
    Gameover go(mainwindow);
    go.lose();
    go.exec();
}

void Game::nextwave()
{
    //qDebug()<<"Num"<<eneNum<<"  curr"<<gameinfo->scene[id].nextwave[current_wave]<<"  id="<<id;
    QPoint startPos=this->gameinfo->scene[id].road_point[0];
    if(eneNum<gameinfo->scene[id].nextwave[current_wave])
    {
        add_enemy(startPos,gameinfo->scene[id].enemy_type[eneNum],this);
        QTimer::singleShot(1000,this,SLOT(nextwave()));
        eneNum++;
    }

    //qDebug()<<"idd"+eneNum;
}

void Game::paintEvent(QPaintEvent *)
{
    QPainter p(this);
    p.drawText(QRect(10,10,100,100),QString::number(i,10));
    p.drawPixmap(0,0,1280,720,bg);
    //qDebug()<<i;
    p.resetTransform();
    p.translate(QCursor::pos()-this->mapToGlobal(QPoint(0,0)));
    if(mouseType)
    {
        int r,R;
        QPixmap pixmap,un_pixmap;
        switch(mouseType)
        {
            case 1:{
                r=25;
                R=200;
                pixmap.load(":/img/turret");
                un_pixmap.load(":/img/un_turret");
                break;
                }
        case 2:{
            r=25;
            R=200;
            pixmap.load(":/img/turret2");
            un_pixmap.load(":/img/un_turret2");
            break;
            }
        case 3:{
            r=25;
            R=200;
            pixmap.load(":/img/turret3");
            un_pixmap.load(":/img/un_turret3");
            break;
            }
        }

        if(judge_turret(QCursor::pos()-this->mapToGlobal(QPoint(0,0)),r))
        {
        QPoint drawPos(-pixmap.width()/2,-pixmap.height()/2);
        p.drawPixmap(drawPos,pixmap);
        p.setPen(QColor(255,255,255,255));
        p.setBrush(QBrush(QColor(255,255,255,100)));
        p.drawEllipse(-R/2,-R/2,R,R);
        createAble=true;
        }
        else //灰色图片
        {
            QPoint drawPos(-pixmap.width()/2,-pixmap.height()/2);
            p.drawPixmap(drawPos,un_pixmap);
            p.setPen(QColor(255,255,255,255));
            p.setBrush(QBrush(QColor(255,255,255,100)));
            p.drawEllipse(-R/2,-R/2,R,R);
            createAble=false;
        }
    }
    p.resetTransform();
    //绘制炮塔
    for(int i=0;i<turret_list.size();i++)
    {
        turret_list.at(i)->draw(&p);
    }

    //绘制敌人
    for(int i=0;i<enemy_list.size();i++)
    {
        enemy_list.at(i)->draw(&p);
    }

    //绘制子弹
    for(int i=0;i<bullet_list.size();i++)
    {
        //qDebug()<<bullet_list.size();
        bullet_list.at(i)->draw(&p);
    }

    for(int i=0;i<boom_list.size();i++)
    {
        boom_list.at(i)->draw(&p);
    }

    p.drawText(10,10,QString::number(i));
}

bool Game::check_bullet(Bullet *bullet)
{
    if(this->bullet_list.indexOf(bullet)==-1)return 0;
    return 1;
}

bool Game::check_turret(Turret *turret)
{
    if(this->turret_list.indexOf(turret)==-1)return 0;
    return 1;
}

bool Game::check_enemy(Enemy *enemy)
{
    if(this->enemy_list.indexOf(enemy)==-1)return 0;
    return 1;
}

void Game::checkHp()
{
    for(int j=0;j<this->enemy_list.size();j++)
    {
        if(this->enemy_list.at(j)->pos==QPoint(1048,620))
        {
            this->currentHp--;
            this->remove_enemy(this->enemy_list.at(j));
            ui->label->setText(QString("%1/%2").arg(currentHp).arg(maxHp));
        }
        if(this->currentHp<=0) lose();
    }
}

void Game::add_turret(QPoint pos,int type,Game *game)
{
    Turret *turret=new Turret(pos,type,game);
    this->turret_list.append(turret);
}

void Game::add_enemy(QPoint pos,int type,Game *game)
{
    Enemy *enemy=new Enemy(pos,type,game);
    this->enemy_list.append(enemy);
}

void Game::add_bullet(int power,int type,int targetType,Game *game,QPoint pos,Enemy *enemy,Turret *turret)
{
    Bullet *bullet=new Bullet(power,type,targetType,game,pos,enemy,turret);
    this->bullet_list.append(bullet);
}

void Game::add_boom(QPoint pos)
{
    Boom *b=new Boom(this,pos);
    this->boom_list.append(b);
}
void Game::remove_enemy(Enemy *enemy)
{
    if(enemy_list.indexOf(enemy)==-1) return;
    add_boom(enemy->getPos());
    this->enemy_list.removeAt(enemy_list.indexOf(enemy));
    delete enemy;
    currEneNum--;
}
void Game::remove_bullet(Bullet *bullet)
{
    if(bullet_list.indexOf(bullet)==-1) return;
    this->bullet_list.removeAt(bullet_list.indexOf(bullet));
    delete bullet;
}
void Game::remove_turret(Turret *turret)
{
    if(turret_list.indexOf(turret)==-1) return;
    this->turret_list.removeAt(turret_list.indexOf(turret));
    delete turret;
}
void Game::remove_boom(Boom *boom)
{
    if(boom_list.indexOf(boom)==-1)return ;
    this->boom_list.removeAt(boom_list.indexOf(boom));
    delete boom;
}




double Game::dis_point_seg(const QPoint p,const QPoint s,const QPoint t)
{
   QPoint v1;
   v1.setX(t.x()-s.x());
   v1.setY(t.y()-s.y());
   QPoint v2;
   v2.setX(p.x()-s.x());
   v2.setY(p.y()-s.y());
   return fabs((v1.x()*v2.y()*1.0-v1.y()*v2.x()*1.0)/(v1.x()*v1.x()*1.0+v1.y()*v1.y()*1.0));
}
bool Game::judge_turret(QPoint pos,double r1)
{
    double r2=1;
    QList<Turret*>::const_iterator it;
    for(it=turret_list.constBegin(); it!=turret_list.constEnd(); ++it)
    {
        if(((*it)->pos.x()-pos.x())*((*it)->pos.x()-pos.x())+((*it)->pos.y()-pos.y())*((*it)->pos.y()-pos.y())<(r1+(*it)->radius)*(r1+(*it)->radius))
            return false;
    }
    return true;

    int roadNum=mainwindow->gameinfo.scene[id].road_point_number;
    QPoint roadPoint[100]=mainwindow->gameinfo.scene[id].road_point;
    //判定两点之间的线和圆是否相交
   /*for(int i=1;i<roadNum;i++)
    {
          QPoint s=roadPoint[i-1];
          QPoint t=roadPoint[i];
          QPoint p=pos;
          if(dis_point_seg(p,s,t)<r1+r2) return false;
    }
    return true;
    */
}

bool Game::pay_money(int money)
{
    if(this->money>=money)
    {
        this->money-=money;
        return true;
    }
    else return false;
}

void Game::earn_money(int money)
{
    this->money+=money;
}


void Game::Pause()
{
    timer->stop();
}

void Game::game_start()
{
    qDebug()<<"game start";
    timer->start();
}

void Game::mousePressEvent(QMouseEvent *event)
{
    if(leveling&&!mouseType)
    {
        leveling=false;
        levelUI->notplay();
    }

    //塔的升级
    if(!mouseType)
    {
        for(int i=0;i<turret_list.size();i++)
        {
            Turret *t=turret_list.at(i);
            QPoint pos=t->getPos();
            double radius=t->radius;
            QPoint mousePos=QCursor::pos()-this->mapToGlobal(QPoint(0,0));
            if(sqrt(mousePos.x()-pos.x())
                   +sqrt(mousePos.y()-pos.y())
                   <sqrt(radius))
            {
                levelUI->play(t);
                leveling=true;
            }
        }
    }

    //塔的创建
    if(mouseType)
    {
        if(createAble)
        {
            add_turret(QCursor::pos()-this->mapToGlobal(QPoint(0,0)),mouseType,this);
            qDebug()<<"first";
            mouseType=0;
            ui->toolB_2->setVisible(false);
        }
        else
        {
            //do something
        }
    }
}

void Game::on_toolB_1_clicked()
{
    if(pay_money(100))
    {
        mouseType=1;
        ui->toolB_2->setVisible(true);
    }
}

void Game::on_toolB_2_clicked() //删除
{
    if(mouseType)
    {
        switch(mouseType)
        {
            case 1:earn_money(100);
        }
        mouseType=0;
        ui->toolB_2->setVisible(false);
    }
}

void Game::on_pushB_1_toggled(bool checked)   //二倍数控制
{
    if(checked)
    {
        timer->setInterval(15);
        timeScale=2;
    }
    else
    {
        timer->setInterval(30);
        timeScale=1;
    }
}

void Game::on_pushB_2_toggled(bool checked)  //暂停开始
{
    if(checked)Pause();
    else game_start();
}

void Game::on_toolB_3_clicked()
{
    mainwindow->option->exec();
}

void Game::on_toolB_4_clicked()
{
    if(pay_money(120))
    {
        mouseType=2;
        ui->toolB_2->setVisible(true);
    }
}

void Game::on_toolB_5_clicked()
{
    if(pay_money(150))
        {
            mouseType=3;
            ui->toolB_2->setVisible(true);
        }
}
